#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   music_init.py
@Time    :   2023/11/09 10:59:41
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
import json
import os
import django

from datetime import datetime
from django.core.management.base import BaseCommand
from django.utils.timezone import make_aware
from django.db import connection

from backend.settings import BASE_DIR
from music.models import Music


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "application.settings")
django.setup()


def main():
    # 打开音乐数据文件，并加载为json格式
    with open(
        os.path.join(BASE_DIR, "utils", "musicdata.json"), "r", encoding="utf-8"
    ) as load_f:
        musics = json.load(load_f)

    # 将JSON字符串转换为带时区的日期时间对象
    DATE_FMT = "%Y-%m-%d %H:%M:%S"
    for track in musics:
        # 将最后一次播放日期时间字符串转换为datetime对象，并设置时区意识
        track_date = datetime.strptime(track["last_play"], DATE_FMT)
        track["last_play"] = make_aware(track_date)

    # 如果数据库中没有音乐对象，则批量创建
    if Music.objects.count() == 0:
        Music.objects.bulk_create([Music(**ele) for ele in musics])
    else:
        # 如果已经有音乐对象，则更新或创建新的对象
        for ele in musics:
            # 删除音乐对象中的id字段
            id = ele.pop("id")
            # 更新或创建音乐对象
            Music.objects.update_or_create(id=id, defaults=ele)


class Command(BaseCommand):
    """
    项目初始化命令: python manage.py music_init
    """

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **kwargs):
        """
        初始化music数据

        :param args: 位置参数
        :param kwargs: 关键字参数
        """
        print(f"正在准备初始化music数据...")
        if hasattr(connection, "tenant") and connection.tenant.schema_name:
            from django_tenants.utils import get_tenant_model
            from django_tenants.utils import tenant_context, schema_context

            for tenant in get_tenant_model().objects.exclude(schema_name="public"):
                with tenant_context(tenant):
                    print(f"租户[{connection.tenant.schema_name}]初始化数据开始...")
                    main()
                    print(f"租户[{connection.tenant.schema_name}]初始化数据完成！")
        else:
            main()
        print("music数据初始化完成")
